import NavBar from '@/components/NavBar';
import Textarea from '@/components/Textarea';
import { useAppSelector } from '@/store';
import {
  GetProfileAction,
  UpdateProfileAction,
  UpdateUserProfileAction,
} from '@/store/action/user';
import { ProfileType } from '@/store/reducer/user';
import { DatePicker, Dialog, List, Popup, Toast } from 'antd-mobile';
import { useEffect, useRef, useState } from 'react';
import { useDispatch } from 'react-redux';
import styles from './index.module.scss';
import dayjs from 'dayjs';
import { RemoveToken } from '@/utils/storage';
import { useHistory } from 'react-router-dom';
type EditType = 'photo' | 'gender' | 'birthday' | 'name' | 'intro';

export default function ProfileEdit() {
  const dispatch = useDispatch();
  /** 首次默认回显数据 */
  useEffect(() => {
    dispatch(GetProfileAction());
  }, [dispatch]);

  const { Profile } = useAppSelector((state) => state.user);

  const [editState, seteditState] = useState('' as EditType);
  const [isShow, setisShow] = useState(false);
  const InputFileRef = useRef<HTMLInputElement>(null);

  /**回显并监听input与textarea数据 */
  const [name, setname] = useState('');
  const [intro, setintro] = useState('');
  useEffect(() => {
    handleEcho(); // eslint-disable-next-line
  }, [Profile[editState]]);

  /** 模态框事件 */
  const ChangeisShow = (type: EditType) => {
    setisShow(true);
    seteditState(type);
  };

  /** file上传事件 */
  async function hanleChangeUpload(e: React.ChangeEvent<HTMLInputElement>) {
    let formdata: any = new FormData();
    if (e.target.files) formdata.append('photo', e.target.files[0]);
    await dispatch(UpdateProfileAction(formdata));
    setisShow(false);
    Toast.show({ icon: 'success', content: '上传头像成功' });
  }

  /** 共用提交事件 */
  const EditProfile = async (data: Partial<ProfileType>) => {
    await dispatch(UpdateUserProfileAction({ ...Profile, ...data }));
    Toast.show('更新成功');
    setisShow(false);
  };

  /** 返回按钮函数 */
  const handleback = () => {
    setisShow(false);
    handleEcho();
  };

  /** 回显复用函数 */
  const handleEcho = () => {
    if (editState === 'name') setname(Profile[editState] || '');
    if (editState === 'intro') setintro(Profile[editState] || '');
  };

  /** 回车以及Esc事件 */
  const handleKeyDown = (
    e: React.KeyboardEvent<HTMLInputElement | HTMLTextAreaElement>,
    EditData: Partial<ProfileType>
  ) => {
    if (e.key === 'Enter') EditProfile(EditData);
    if (e.key === 'Escape') {
      setname('');
      setintro('');
    }
  };

  const history = useHistory();
  /** 退出登录事件 */
  const handleExit = async () => {
    const result = await Dialog.confirm({
      title: '温馨提示',
      content: '亲,您确定要退出吗?',
      cancelText: <span style={{ color: '#000' }}>取消</span>,
      confirmText: <span style={{ fontWeight: 400 }}>确认</span>,
    });
    if (result) {
      RemoveToken();
      history.replace('/login');
      Toast.show({ content: '退出登录成功', position: 'bottom' });
    }
  };

  return (
    <div className={styles.root}>
      <div className="content">
        {/* 顶部导航栏 */}
        <NavBar>个人资料</NavBar>

        <div className="wrapper">
          {/* 列表一：显示头像、昵称、简介 */}
          <List className="profile-list">
            <List.Item
              arrow
              onClick={() => ChangeisShow('photo')}
              extra={<img className="avatar" src={Profile.photo} alt="" />}
            >
              头像
            </List.Item>

            <List.Item
              arrow
              extra={Profile.name}
              onClick={() => ChangeisShow('name')}
            >
              昵称
            </List.Item>

            <List.Item
              arrow
              extra={<span className="intro">{Profile.intro || '未填写'}</span>}
              onClick={() => ChangeisShow('intro')}
            >
              简介
            </List.Item>

            <List.Item
              arrow
              extra={Profile.gender === 0 ? '男' : '女'}
              onClick={() => ChangeisShow('gender')}
            >
              性别
            </List.Item>
            <List.Item
              arrow
              extra={Profile.birthday}
              onClick={() => ChangeisShow('birthday')}
            >
              生日
            </List.Item>
          </List>

          {/* 文件选择框，用于头像图片的上传 */}
          <input className="avatar-upload" type="file" />
        </div>

        {/* 底部栏：退出登录按钮 */}
        <div className="logout">
          <button className="btn" onClick={handleExit}>
            退出登录
          </button>
        </div>
      </div>
      <input
        type="file"
        ref={InputFileRef}
        id="file"
        onChange={(e) => hanleChangeUpload(e)}
      />

      {editState === 'name' || editState === 'intro' ? (
        /* 右侧弹出层 */
        <Popup
          visible={isShow}
          destroyOnClose
          onMaskClick={() => setisShow(false)}
          position="right"
          bodyStyle={{ minWidth: '100vw' }}
          className="popup-right"
        >
          <NavBar
            onBack={handleback}
            right={
              <span
                className="submit-btn"
                onClick={() =>
                  EditProfile({
                    [`${editState}`]: editState === 'name' ? name : intro,
                  })
                }
              >
                提交
              </span>
            }
          >
            {editState === 'name' ? '编辑昵称' : '编辑简介'}
          </NavBar>
          <div className="edit-content">
            {editState === 'name' && (
              <input
                className="edit-input"
                placeholder="请输入内容"
                value={name}
                autoFocus
                onKeyDown={(e) => handleKeyDown(e, { name })}
                onChange={(e) => setname(e.target.value)}
              />
            )}
            {editState === 'intro' && (
              <Textarea
                value={intro}
                onChange={(e) => setintro(e.target.value)}
                maxLength={200}
                onKeyDown={(e) => handleKeyDown(e, { intro })}
              ></Textarea>
            )}
          </div>
        </Popup>
      ) : (
        /* 底部弹出层 */
        <Popup
          visible={isShow}
          position="bottom"
          bodyClassName="popup-bottom-list"
          onMaskClick={() => setisShow(false)}
        >
          {editState === 'photo' && (
            <>
              <div
                className="list-item"
                onClick={() => InputFileRef.current?.click()}
              >
                拍照
              </div>
              <div
                className="list-item"
                onClick={() => InputFileRef.current?.click()}
              >
                本地选择
              </div>
              <div className="list-item" onClick={() => setisShow(false)}>
                取消
              </div>
            </>
          )}
          {editState === 'gender' && (
            <>
              <div
                className="list-item"
                onClick={() => EditProfile({ gender: 0 })}
              >
                男
              </div>
              <div
                className="list-item"
                onClick={() => EditProfile({ gender: 1 })}
              >
                女
              </div>
              <div className="list-item" onClick={() => setisShow(false)}>
                取消
              </div>
            </>
          )}
          {editState === 'birthday' && (
            <DatePicker
              className="antd-submit-color"
              title="选择生日"
              min={new Date('1960-01-01')}
              max={new Date()}
              visible={isShow}
              defaultValue={new Date(Profile.birthday)}
              onClose={() => setisShow(false)}
              onConfirm={(val) =>
                EditProfile({ birthday: dayjs(val).format('YYYY-MM-DD') })
              }
            />
          )}
        </Popup>
      )}
    </div>
  );
}
